package com.example.tool.util.aliyun;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.tool.util.DateUtil;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryResult;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryTrack;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AliYunExpressDeliveryUtil {
    //回调地址
    private static final String callback="http://47.93.37.107:8080/tool/dd/callback";
    //快递查询appcode
    //快递订阅推送appcode
    private static final String appcode="bea41f6d3741490a92aa6eadcb5b6d10";
    public static void main(String[] args) {
//       queryLogistics("621210641259172");//菜鸟
//       queryLogistics("JT3127608765414");//极兔
//       queryLogistics("773367542133350");//申通
//       queryLogistics("SF3192865847900");//顺丰
//       queryLogistics("YT8780067718823");//圆通
//        queryLogistics("434669515618317");//韵达
//       queryLogistics("78924794420854");//中通
//       queryLogistics("1398665420502");//EMS
//       queryLogistics("773366676969537");//京东
       queryLogistics("500202113394");//安能
//      ExpressPushSubscribe("JT3122530281376");
    }

//    public static void main(String[] args) {
//        String host = "https://kzexpress.market.alicloudapi.com";
//        String path = "/api-mall/api/express/query";
//        String method = "GET";
//        Map<String, String> headers = new HashMap<String, String>();
//        headers.put("Authorization", "APPCODE " + appcode);
//        Map<String, String> querys = new HashMap<String, String>();
//        querys.put("expressNo", "78884316533292");
//        try {
//            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
//            JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
//            System.out.println(jsonObject);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
    public static ExpressDeliveryResult queryLogistics(String waybillNo){
        ExpressDeliveryResult result = new ExpressDeliveryResult();
        result.setWaybillNo(waybillNo);
        String host = "https://kzexpress.market.alicloudapi.com";
        String path = "/api-mall/api/express/query";
        String method = "GET";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("expressNo",waybillNo);
        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            System.out.println(response.toString());
            JSONObject iResult = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
//            JSONObject iResult= JSONObject.parseObject("{\"msg\":\"成功\",\"code\":200,\"data\":{\"cpCode\":\"JTSD\",\"mailNo\":\"JT3122530281376\",\"theLastTime\":\"2025-06-08 18:37:12\",\"cpMobile\":\"\",\"theLastMessage\":\"包裹已签收！（凭取件码）如有问题请联系：瑞园新村菜鸟驿站 15252776639，投诉电话：0514-84774884\",\"orderNo\":\"202507170940084818075\",\"logisticsCompanyName\":\"极兔速递\",\"cpUrl\":\"\",\"logisticsStatusDesc\":\"已签收\",\"logisticsTraceDetailList\":[{\"areaCode\":\"\",\"areaName\":\"合肥市\",\"subLogisticsStatus\":\"ACCEPT\",\"timeDesc\":\"2025-06-06 19:26:04\",\"time\":1749209164000,\"logisticsStatus\":\"ACCEPT\",\"desc\":\"【合肥市肥西柏堰网点】的装卸揽专用（19355991735）已取件，投诉电话：0551-64653533\"},{\"areaCode\":\"\",\"areaName\":\"合肥市\",\"subLogisticsStatus\":\"TRANSPORT\",\"timeDesc\":\"2025-06-06 19:26:14\",\"time\":1749209174000,\"logisticsStatus\":\"TRANSPORT\",\"desc\":\"快件离开【合肥市肥西柏堰网点】已发往【合肥转运中心】\"},{\"areaCode\":\"\",\"areaName\":\"合肥市\",\"subLogisticsStatus\":\"TRANSPORT\",\"timeDesc\":\"2025-06-06 21:13:51\",\"time\":1749215631000,\"logisticsStatus\":\"TRANSPORT\",\"desc\":\"快件到达【合肥转运中心】\"},{\"areaCode\":\"\",\"areaName\":\"合肥市\",\"subLogisticsStatus\":\"TRANSPORT\",\"timeDesc\":\"2025-06-06 21:22:20\",\"time\":1749216140000,\"logisticsStatus\":\"TRANSPORT\",\"desc\":\"快件离开【合肥转运中心】已发往【芜湖转运中心】\"},{\"areaCode\":\"\",\"areaName\":\"芜湖市\",\"subLogisticsStatus\":\"TRANSPORT\",\"timeDesc\":\"2025-06-06 21:28:22\",\"time\":1749216502000,\"logisticsStatus\":\"TRANSPORT\",\"desc\":\"快件到达【芜湖转运中心】\"},{\"areaCode\":\"\",\"areaName\":\"芜湖市\",\"subLogisticsStatus\":\"TRANSPORT\",\"timeDesc\":\"2025-06-06 22:57:56\",\"time\":1749221876000,\"logisticsStatus\":\"TRANSPORT\",\"desc\":\"快件离开【芜湖转运中心】已发往【南京转运中心】\"},{\"areaCode\":\"\",\"areaName\":\"南京市\",\"subLogisticsStatus\":\"TRANSPORT\",\"timeDesc\":\"2025-06-07 01:01:55\",\"time\":1749229315000,\"logisticsStatus\":\"TRANSPORT\",\"desc\":\"快件到达【南京转运中心】\"},{\"areaCode\":\"\",\"areaName\":\"南京市\",\"subLogisticsStatus\":\"TRANSPORT\",\"timeDesc\":\"2025-06-07 07:22:00\",\"time\":1749252120000,\"logisticsStatus\":\"TRANSPORT\",\"desc\":\"快件离开【南京转运中心】已发往【扬州仪征乡镇网点】\"},{\"areaCode\":\"\",\"areaName\":\"扬州市\",\"subLogisticsStatus\":\"TRANSPORT\",\"timeDesc\":\"2025-06-07 08:01:00\",\"time\":1749254460000,\"logisticsStatus\":\"TRANSPORT\",\"desc\":\"快件到达【扬州仪征乡镇网点】\"},{\"areaCode\":\"\",\"areaName\":\"扬州市\",\"subLogisticsStatus\":\"DELIVERING\",\"timeDesc\":\"2025-06-07 10:27:41\",\"time\":1749263261000,\"logisticsStatus\":\"DELIVERING\",\"desc\":\"【扬州仪征乡镇网点】的兔兔快递员：瑞园新村菜鸟驿站（15252776639）正在为您派件（有事先呼我，勿找平台，少一次投诉，多一份感恩！），投诉电话（0514-84774884）。【952300为极兔快递员外呼专属号码，请放心接听】\"},{\"areaCode\":\"\",\"areaName\":\"扬州市\",\"subLogisticsStatus\":\"RETENTION\",\"timeDesc\":\"2025-06-07 10:54:08\",\"time\":1749264848000,\"logisticsStatus\":\"SIGN\",\"desc\":\"您的包裹已存放至【菜鸟驿站】，记得早点来【扬州仪征瑞园新村店】取它回家！如有问题请联系：菜鸟驿站 19707677920/瑞园新村菜鸟驿站 19707677920，投诉电话：0514-84774884\"},{\"areaCode\":\"\",\"areaName\":\"扬州市\",\"subLogisticsStatus\":\"SIGN\",\"timeDesc\":\"2025-06-08 18:37:12\",\"time\":1749379032000,\"logisticsStatus\":\"SIGN\",\"desc\":\"包裹已签收！（凭取件码）如有问题请联系：瑞园新村菜鸟驿站 15252776639，投诉电话：0514-84774884\"}],\"logisticsStatus\":\"SIGN\"},\"success\":true}\n");
            System.out.println(iResult.toJSONString());
            Boolean success = iResult.getBoolean("success");
            result.setSucceed(success);
            if(success){
                List<ExpressDeliveryTrack> tracks=new ArrayList<>();
                JSONObject data=iResult.getJSONObject("data");
                JSONArray logisticsTraceDetailList=data.getJSONArray("logisticsTraceDetailList");
                for(int i=0;i<logisticsTraceDetailList.size();i++){
                    JSONObject ltDetails = logisticsTraceDetailList.getJSONObject(i);
                    Date time = DateUtil.toDate(ltDetails.getString("time"));
                    String desc = ltDetails.getString("desc");
                    String logisticsStatus = ltDetails.getString("subLogisticsStatus");
                    ExpressDeliveryTrack track = new ExpressDeliveryTrack();
                    track.setDesc(desc);
                    track.setScanDate(time);
                    track.setScanType(logisticsStatus);
                    tracks.add(track);
                }
                result.setTracks(tracks);
//            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    public static void ExpressPushSubscribe(String waybillNo){
        String host = "https://kzeprpush.market.alicloudapi.com";
        String path = "/api/express/push";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("callback", callback);
//        bodys.put("mobile", "mobile");
        bodys.put("expressNo", waybillNo);
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            String string = EntityUtils.toString(response.getEntity());
            System.out.println(JSONObject.parseObject(string));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
